package com.api.user.service.impl;

import com.api.base.dao.SysUserRoleMapper;
import com.api.base.dao.UserMapper;
import com.api.base.model.SysUserRole;
import com.api.base.model.User;
import com.api.common.EmailUtil;
import com.api.common.JSONUtils;
import com.api.common.mybatis.ResultMap;
import com.api.core.config.AuthUser;
import com.api.core.response.Result;
import com.api.core.response.ResultGenerator;
import com.api.core.service.AbstractService;
import com.api.user.dao.ManageInfoMapper;
import com.api.user.dao.UserInfoMapper;
import com.api.user.model.ManageExamineLog;
import com.api.user.model.ManageInfo;
import com.api.user.model.UserInfo;
import com.api.user.service.ManageExamineLogService;
import com.api.user.service.ManageInfoService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

import static com.api.user.enums.IdentificationStatusEnums.USER_LEVEL_NA;

/**
 * Created by wanghuiwen on 2021/03/25.
 */
@Service
@Transactional
public class ManageInfoServiceImpl extends AbstractService<ManageInfo> implements ManageInfoService {
    @Resource
    private ManageInfoMapper manageInfoMapper;

    @Resource
    private ManageExamineLogService manageExamineLogService;
    @Resource
    private UserInfoMapper userInfoMapper;
    @Resource
    private SysUserRoleMapper sysUserRoleMapper;
    @Resource
    private UserMapper userMapper;


    @Override
    public Result list(Map<String, Object> params, String order, Integer page, Integer size){
//        Map<String, Object> params = JSONUtils.json2map(search);
        Map<String, Object> orderParams = JSONUtils.json2map(order);
        for (String key : orderParams.keySet()) {
                if (orderParams.get(key) != null && orderParams.get(key).equals("ascending")) orderParams.put(key, "asc");
                if (orderParams.get(key) != null && orderParams.get(key).equals("descending")) orderParams.put(key, "desc");
            }
        PageHelper.startPage(page, size);
        orderParams.put("m.user_id","desc");
        List<Map<String, Object>> res = manageInfoMapper.list(params, orderParams);
        PageInfo<Map<String, Object>> pageInfo = new PageInfo<>(res);
        return ResultGenerator.genSuccessResult(pageInfo);
    }

    @Override
    public Result add(ManageInfo manageInfo) {

        ManageInfo manageInfo1 = this.findById(manageInfo.getUserId());
        if(manageInfo1!=null){
            this.update(manageInfo);
        }else{
            this.save(manageInfo);
        }

        ManageExamineLog manageExamineLog = new ManageExamineLog();
        manageExamineLog.setManageId(manageInfo.getUserId());
        manageExamineLog.setStatus("1");
        manageExamineLog.setFrontUrl(manageInfo.getFrontUrl());
        manageExamineLog.setBackUrl(manageInfo.getBackUrl());
        manageExamineLogService.save(manageExamineLog);

        return ResultGenerator.genSuccessResult();
    }

    @Override
    public Result examine(ManageExamineLog manageExamineLog) {
        ManageInfo manageInfo = this.findById(manageExamineLog.getUserId());
        manageInfo.setExamine(Integer.parseInt(manageExamineLog.getStatus()));
        this.update(manageInfo);


        manageExamineLog.setCreateDate(new Date().getTime());
        manageExamineLogService.update(manageExamineLog);
        return ResultGenerator.genSuccessResult();
    }

    @Override
    public Result detail(Long userId) {
        return ResultGenerator.genSuccessResult(manageInfoMapper.detail(userId));
    }

    @Override
    public Result updateManager(UserInfo userInfo, ManageInfo manageInfo) {

        manageInfo.setUpdateTime(new Date().getTime());
        userInfoMapper.updateByPrimaryKeySelective(userInfo);
        if(manageInfo.getUserId()==null){
            manageInfo.setUserId(userInfo.getUserId());
            manageInfoMapper.insertSelective(manageInfo);
        }else {
            manageInfoMapper.updateByPrimaryKeySelective(manageInfo);
        }
        return ResultGenerator.genSuccessResult();
    }

    @Override
    public Result invitation(AuthUser authUser) {
        List<ResultMap<String,Object>> res = manageInfoMapper.invitation(authUser.getId());
        return ResultGenerator.genSuccessResult(res);
    }

    @Override
    public Result invita(String email, String fullName, String password, AuthUser authUser) {
        User user = userInfoMapper.findByLoginName(email);
        if(user!=null){
            return ResultGenerator.genFailResult(400,"User name has registered");
        }

        user = new User();
        user.setLoginName(email);
        user.setPassword(new BCryptPasswordEncoder().encode(password));
        user.setRegisterTime(new Date().getTime());
        user.setType(3);
        userMapper.insertSelective(user);

        UserInfo userInfo = new UserInfo();
        userInfo.setUserId(user.getId());
        userInfo.setFullName(fullName);
        userInfo.setEmail(email);
        userInfo.setVipLevel(USER_LEVEL_NA);
        userInfoMapper.insert(userInfo);

        ManageInfo manageInfo = new ManageInfo();
        manageInfo.setOrganizer(authUser.getId());
        manageInfo.setUserId(user.getId());
        manageInfoMapper.insert(manageInfo);

        //保存用户角色
        SysUserRole sysUserRole = new SysUserRole();
        sysUserRole.setUserId(user.getId());
        sysUserRole.setRoleId(3);
        sysUserRoleMapper.insert(sysUserRole);

        EmailUtil.gmailSender(email,"Hello, please remember to check in so you can join the tournament",null);

        return ResultGenerator.genSuccessResult();
    }

    @Override
    public Result invitationRemove(Long userId, Boolean disable) {
        User user = userMapper.selectByPrimaryKey(userId);
        user.setDisable(true);
        userMapper.updateByPrimaryKey(user);
        return ResultGenerator.genSuccessResult();
    }

    @Override
    public Result block(Long userId, Boolean block) {
        ManageInfo info = manageInfoMapper.selectByPrimaryKey(userId);
        info.setBlock(block);
        update(info);
        User user = userMapper.selectByPrimaryKey(userId);
        user.setDisable(block);
        userMapper.updateByPrimaryKey(user);
        return ResultGenerator.genSuccessResult();
    }

    @Override
    public List<Map<String, Object>> export(Map<String, Object> params, String order) {
        Map<String, Object> orderParams = JSONUtils.json2map(order);
        for (String key : orderParams.keySet()) {
            if (orderParams.get(key) != null && orderParams.get(key).equals("ascending")) orderParams.put(key, "asc");
            if (orderParams.get(key) != null && orderParams.get(key).equals("descending")) orderParams.put(key, "desc");
        }
        orderParams.put("m.user_id","desc");
        return manageInfoMapper.list(params, orderParams);
    }
}
